package com.kang.gaklibrary.controller;

import com.kang.gaklibrary.mapper.TransactionMapper;
import com.kang.gaklibrary.model.Transaction;
import com.kang.gaklibrary.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.*;
import java.util.Date;

@Controller
@RequestMapping("/index")
public class IndexController {
    @Autowired
    private TransactionMapper transactionMapper;


    // 检查账户登录
    public User check(HttpServletRequest request){
        User user = null;
        HttpSession session = request.getSession(false);
        if (session != null){
            user = (User) session.getAttribute("user");
        }
        return user;
    }

    @RequestMapping("/buy")
    @ResponseBody
    public boolean buy(Long id, HttpServletRequest request, Model model){
        User user = check(request);
        if (user != null){
            Transaction transaction = new Transaction();
            transaction.setDate(new Timestamp(new Date().getTime()));
            transaction.setUserId(user.getUserId());
            transaction.setGoodId(id);
            transaction.setGoodRole(0);
            int i = transactionMapper.insertSelective(transaction);
            if (i > 0){
                return true;
            }
//            Goods goods = goodsMapper.selectByPrimaryKey(id);
//            GoodsRecord goodsRecord = new GoodsRecord(goods.getGoodId(), goods.getGoodName(), goods.getGoodPrice(), goods.getGoodBusiness(), goods.getGoodNumber(), goods.getGoodLocation()
//                    , new Date());
//            System.out.println("....................................................");
//            System.out.println(goods.getGoodName());
//            System.out.println(goodsRecord.getGoodName());
//            int i = goodsRecordMapper.insertGoodsRecord(goodsRecord);
//            System.out.println("....................................................");
//            System.out.println(goodsRecord.getGoodId() + "................");
//            System.out.println(i);
//            if (i > 0){
//                return 1;
//            }
        }
        return false;
    }
}
